package com.iflytek.yly.jetpackdemo.livedata;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.iflytek.yly.jetpackdemo.R;

public class TimerWithLiveDataActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_livedata_timer);
        initComponent();
    }

    private void initComponent(){

        final TextView tvTime = findViewById(R.id.tvTime);
        //通过ViewModelProvider 得到 ViewModel
        TimerWithLiveDataViewModel timerWithLiveDataViewModel = new ViewModelProvider(this)
                .get(TimerWithLiveDataViewModel.class);

        // 得到ViewModel中的LiveData
        final MutableLiveData<Integer> liveData =
                (MutableLiveData<Integer>) timerWithLiveDataViewModel.getCurrentSecond();
        // 通过LiveData.observe()观察ViewModel中数据的变化
        liveData.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer second) {
                //收到回调后更新UI界面
                tvTime.setText("Time : " + second);
            }
        });

        findViewById(R.id.tvResetTime).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //通过LiveData.setValue/LiveData.postValue()完成对ViewModel中数据的更新
                liveData.setValue(0);
            }
        });

        // 计时开始
        timerWithLiveDataViewModel.startTiming();
    }

}
